package com.berwin.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.berwin.entity.SharedText;
import com.berwin.syncer.MainActivity;
import com.berwin.syncer.R;
import com.berwin.utility.ClipboardUtility;


import java.util.ArrayList;
import java.util.List;

public class TextAdapter extends BaseAdapter {

    private class ViewHolder {
        public TextView tvSender;
        public TextView tvContent;
        public Button btnCopy;
    }

    private List<SharedText> model;
    private Context context;
    private LayoutInflater inflater;
    private MainActivity activity;

    public TextAdapter(Context context) {
        this.context = context;
        this.activity = (MainActivity) context;
        this.model = new ArrayList<>();
        this.inflater = LayoutInflater.from(this.context);
    }

    @Override
    public int getCount() {
        return this.model.size();
    }

    public void removeAll() {
        this.model.clear();
    }

    public void addItem(SharedText sharedText) {
        this.model.add(sharedText);
    }

    public void addItem(int i, SharedText sharedText) {
        this.model.add(i, sharedText);
    }

    @Override
    public SharedText getItem(int position) {
        return this.model.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        final SharedText sharedText = this.getItem(position);
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = this.inflater.inflate(R.layout.text_item, parent, false);
            viewHolder.tvContent = convertView.findViewById(R.id.tv_content);
            viewHolder.tvSender = convertView.findViewById(R.id.tv_sender);
            viewHolder.btnCopy = convertView.findViewById(R.id.btn_copy);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.tvSender.setText(sharedText.getSender());
        viewHolder.tvContent.setText(sharedText.getContent());
        viewHolder.btnCopy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextAdapter.this.activity.setLastClipboardContent(sharedText.getContent());
                ClipboardUtility.copy(TextAdapter.this.context, sharedText.getContent());
                TextAdapter.this.activity.showTip("复制成功");
            }
        });
        return convertView;
    }
}
